package com.shitou.springai1.user.service;

import jakarta.annotation.PostConstruct;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ai.document.Document;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class RedisVectorStoreService {

    @Autowired
    private RedisVectorStore redisVectorStore;

    @PostConstruct
    // 创建文档列表
    public void init() {
        // 1. 准备要存储的文档（使用Spring AI的Document类）
        List<Document> documents = List.of(
            new Document(
                "Spring AI 允许你构建强大的基于人工智能的应用程序。它简化了与AI模型的集成。",
                Map.of("framework", "Spring AI", "category", "Introduction")
            ),
            new Document(
                "Redis是一个快速的内存数据结构存储，可用作数据库、缓存和消息代理。",
                Map.of("technology", "Redis", "category", "Overview")
            ),
            new Document(
                "向量相似性搜索通过比较数值向量来找到语义上相似的内容，是RAG的核心。",
                Map.of("concept", "Vector Similarity Search", "application", "RAG")
            ),
            new Document(
                "OpenAI的text-embedding模型可以将文本转换为高维向量表示。",
                Map.of("provider", "OpenAI", "model-type", "Embedding")
            ),
                new Document(
                        "spring",
                        Map.of("provider", "spring", "model-type", "Embedding")
            ),
                new Document(
                        "spring 是真的不错啊",
                        Map.of("provider", "springss", "model-type", "Embedding")
                ),
                new Document(
                        "张凯是个好人呢"
                        )

        );

        // 2. 添加文档到Redis
        redisVectorStore.add(documents);
    }

    // 搜索文档
    public List<Document> search( String  str) {
        SearchRequest request = SearchRequest
                .builder()
                .query(str)
                .topK(1)
                .similarityThreshold(0.8f)
                .build();


        List<org.springframework.ai.document.Document> results = redisVectorStore.
                similaritySearch(request);

        if (results.isEmpty()) {
            System.out.println("没有找到匹配的文档");
        } else {
            System.out.println("找到以下匹配的文档：");
            for (Document document : results) {
                System.out.println("内容: " + document.getText());
                System.out.println("元数据: " + document.getMetadata());
                System.out.println("---");
            }
        }
        return results;
    }
}
